﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Globalization;
using RPSImporter.Services.Data;
using RPSImporter.Services;

namespace RPSImporter.Infrastructure
{
    public class ModelBase
    {
        public ModelBase()
        {
            this.Data = new Dictionary<string, string>();
        }

        protected virtual RpsDBDataContext DB
        {
            get
            {
                return DatabaseSvc.Instance.DBContext;
            }
        }

        public virtual string Error { get; set; }

        public virtual Dictionary<string, string> Data { get; set; }

        protected virtual string GetData(string key)
        {
            if (this.Data.ContainsKey(key))
            {
                return this.Data[key];
            }
            else
            {
                this.Error = "Colonne '" + key + "' n'est pas trouvable";
                return String.Empty;
            }
        }

        protected virtual DateTime? GetDataAsDate(string key)
        {
            string value = this.Data.ContainsKey(key) ? this.Data[key] : String.Empty;

            if (value != String.Empty)
            {
                DateTime date;
                if (DateTime.TryParse(value, out date))
                {
                    return date;
                }
            }
            return null;
        }

        protected virtual double? GetDataAsDouble(string key)
        {
            if (this.Data.ContainsKey(key))
            {
                return Convert.ToDouble(this.Data[key]);
            }
            else
            {
                this.Error = "Colonne '" + key + "' n'est pas trouvable";
                return (double?)null;
            }
        }

        protected virtual int? GetMonthNumber(string month)
        {
            var culture = CultureInfo.CreateSpecificCulture("fr-FR");

            if (culture.DateTimeFormat.MonthNames.Any(m => m.ToLower() == month.ToLower()) || culture.DateTimeFormat.MonthNames.Any(m => m.ToLower().Replace('é', 'e') == month.ToLower()) || culture.DateTimeFormat.MonthNames.Any(m => m.ToLower().Replace('û', 'u') == month.ToLower()))
            {
                int monthNr = culture.DateTimeFormat.MonthNames.Select(m => m.ToLower()).ToList().IndexOf(month.ToLower());
                return monthNr + 1;
            }
            return (int?)null;
        }
    }
}